# -*- coding: UTF-8 -*-
# @Time : 2022/1/17 0017 17:21
# @Author : lyw
# @Remark :
import logging

from mxsoftpy import DB
from mxsoftpy.exception import DBError

from utils.classes.custom_exception import VerifyError
from index import _


class JanitorBase(DB):
    def query_brand(self, origin_id):
        """查找品牌信息"""
        try:
            brand_data = self.tree.open("Janitor", "data_origin_conf\\%s" % origin_id, file="IOT").items()

            brand_sub_data = self.tree.open("Janitor", "data_origin_conf\\%s" % origin_id, file="IOT").sub_items()
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询错误"))
        return brand_data, brand_sub_data

    def query_host(self, data_origin=None, **kwargs):
        """
        获取数据源
        @param data_origin: 数据源id
        @param kwargs: 查询的条件
        @return:
        """
        try:
            if not data_origin:
                total, data_origin = self.tree.open("Janitor", "data_origin", file="IOT").filter(**kwargs)
            else:
                data_origin = [data_origin]
            if data_origin:
                data_info = self.tree.open("Janitor", "data_origin\\%s" % data_origin[0], file="IOT").items()
                return data_origin[0], data_info

        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询错误"))

        return None, {}

    def get_field(self, sub_key):
        """
        获取字段
        @param sub_key:
        @return:
        """
        try:
            field_data = self.tree.open("Janitor", "config_field\\%s" % sub_key, file="IOT").sub_items()
            res_list = []
            for key, value in field_data.items():
                value["index"] = key
                res_list.append(value)
        except DBError as e:
            logging.error(e)
            raise VerifyError(_("查询错误"))
        return res_list
